/**
 * API错误类
 */
export class ApiError extends Error {
  status: number;
  data: any;

  constructor(message: string, status: number, data?: any) {
    super(message);
    this.name = 'ApiError';
    this.status = status;
    this.data = data;
  }
}

// 请求方法类型
type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';

// 请求选项接口
interface RequestOptions {
  method?: HttpMethod;
  headers?: Record<string, string>;
  body?: any;
  credentials?: RequestCredentials;
  cache?: RequestCache;
}

/**
 * 发送API请求
 */
export async function fetchApi<T = any>(
  endpoint: string,
  options: RequestOptions = {}
): Promise<T> {
  const {
    method = 'GET',
    headers = {},
    body,
    credentials = 'include',
    cache = 'default',
  } = options;

  // 构建完整URL
  let url = endpoint;
  
  // 如果不是完整URL（不包含http或https），并且不是以/api开头
  if (!url.match(/^https?:\/\//) && !url.startsWith('/api')) {
    // 如果已经有/前缀，则添加api，否则添加/api/
    url = url.startsWith('/') ? `/api${url}` : `/api/${url}`;
  }
  
  // 添加API基础URL
  const API_BASE_URL = process.env.NEXT_PUBLIC_API_URL || '';
  url = `${API_BASE_URL}${url}`;
  
  console.log(`【API请求】构建URL: ${endpoint} -> ${url}`);

  // 设置默认请求头
  const defaultHeaders: Record<string, string> = {
    'Content-Type': 'application/json',
    'Accept': 'application/json',
  };

  // 合并请求头
  const requestHeaders = { ...defaultHeaders, ...headers };

  // 构建请求选项
  const requestOptions: RequestInit = {
    method,
    headers: requestHeaders,
    credentials,
    cache,
  };

  // 添加请求体（如果有）
  if (body) {
    requestOptions.body = JSON.stringify(body);
  }

  try {
    console.log(`【API请求】${method} ${url}`);
    if (body) {
      console.log('【API请求】请求数据:', body);
    }
    
    const response = await fetch(url, requestOptions);
    console.log(`【API响应】状态: ${response.status} ${response.statusText}`);
    
    // 检查响应状态
    if (!response.ok) {
      let errorData;
      const contentType = response.headers.get('Content-Type') || '';
      
      try {
        if (contentType.includes('application/json')) {
          errorData = await response.json();
        } else {
          const textResponse = await response.text();
          errorData = { message: textResponse || response.statusText };
        }
      } catch (e) {
        errorData = { message: `无法解析错误响应: ${response.statusText}` };
      }

      throw new ApiError(
        errorData.message || `请求失败: ${response.status}`,
        response.status,
        errorData
      );
    }

    // 解析响应数据
    const contentType = response.headers.get('Content-Type') || '';
    
    if (contentType.includes('application/json')) {
      const jsonResponse = await response.json();
      return jsonResponse as T;
    } else {
      const textResponse = await response.text();
      return textResponse as unknown as T;
    }
  } catch (error) {
    if (error instanceof ApiError) {
      throw error;
    }

    console.error('【API错误】请求失败:', error);
    throw new ApiError(
      error instanceof Error ? error.message : '网络请求失败',
      0,
      { originalError: error }
    );
  }
}

/**
 * 带错误处理的API请求
 * 
 * 这是fetchApi的包装器，提供额外的错误处理
 */
export async function fetchWithErrorHandling<T = any>(
  url: string,
  options: RequestInit = {}
): Promise<T> {
  try {
    // 转换RequestInit为RequestOptions
    const apiOptions: RequestOptions = {
      method: options.method as HttpMethod,
      headers: options.headers as Record<string, string>,
      body: options.body,
      credentials: options.credentials,
      cache: options.cache,
    };
    
    return await fetchApi<T>(url, apiOptions);
  } catch (error) {
    // 如果是ApiError，直接抛出
    if (error instanceof ApiError) {
      throw error;
    }
    
    // 其他错误转换为ApiError
    console.error('请求失败:', error);
    throw new ApiError(
      error instanceof Error ? error.message : '请求失败',
      500,
      { originalError: error }
    );
  }
}

/**
 * API客户端
 */
export const api = {
  /**
   * 发送GET请求
   */
  get: <T = any>(endpoint: string, options: Omit<RequestOptions, 'method' | 'body'> = {}) => {
    return fetchApi<T>(endpoint, { ...options, method: 'GET' });
  },

  /**
   * 发送POST请求
   */
  post: <T = any>(endpoint: string, data?: any, options: Omit<RequestOptions, 'method' | 'body'> = {}) => {
    return fetchApi<T>(endpoint, { ...options, method: 'POST', body: data });
  },

  /**
   * 发送PUT请求
   */
  put: <T = any>(endpoint: string, data?: any, options: Omit<RequestOptions, 'method' | 'body'> = {}) => {
    return fetchApi<T>(endpoint, { ...options, method: 'PUT', body: data });
  },

  /**
   * 发送PATCH请求
   */
  patch: <T = any>(endpoint: string, data?: any, options: Omit<RequestOptions, 'method' | 'body'> = {}) => {
    return fetchApi<T>(endpoint, { ...options, method: 'PATCH', body: data });
  },

  /**
   * 发送DELETE请求
   */
  delete: <T = any>(endpoint: string, options: Omit<RequestOptions, 'method'> = {}) => {
    return fetchApi<T>(endpoint, { ...options, method: 'DELETE' });
  },
};

/**
 * 用户相关API
 */
export const userApi = {
  /**
   * 获取当前用户信息
   */
  getCurrentUser: async () => {
    try {
      // 明确使用api前缀，虽然现在fetchApi会自动添加，但为了代码清晰还是明确标注
      return await api.get('/api/users/me');
    } catch (error) {
      console.error('获取当前用户信息失败:', error);
      throw new Error('获取当前用户信息失败');
    }
  },

  /**
   * 获取用户资料
   */
  getUserProfile: async (userId: string) => {
    try {
      // 确保请求发送到正确的端点并带有凭证
      const response = await fetch(`/api/user/${userId}/profile`, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json',
        },
        credentials: 'include',
      });

      if (!response.ok) {
        const errorData = await response.json();
        console.error('获取用户资料请求失败:', errorData);
        throw new Error(errorData.error || '获取用户资料失败');
      }

      return await response.json();
    } catch (error) {
      console.error('获取用户资料失败:', error);
      throw new Error('获取用户资料失败');
    }
  },

  /**
   * 更新用户资料
   */
  updateUserProfile: async (data: any) => {
    try {
      console.log('开始更新用户资料:', data);
      
      // 确保数据格式正确
      const cleanedData = { ...data };
      
      // 预处理socialLinks确保它是对象
      if (cleanedData.socialLinks && typeof cleanedData.socialLinks === 'string') {
        try {
          cleanedData.socialLinks = JSON.parse(cleanedData.socialLinks);
        } catch (e) {
          console.warn('socialLinks解析失败，使用空对象替代');
          cleanedData.socialLinks = {};
        }
      }
      
      // 确保skills是数组
      if (cleanedData.skills && !Array.isArray(cleanedData.skills)) {
        if (typeof cleanedData.skills === 'string') {
          cleanedData.skills = cleanedData.skills.split(',').map((s: string) => s.trim());
        } else {
          cleanedData.skills = [];
        }
      }
      
      // 直接发送请求到API端点
      const response = await fetch('/api/user/profile', {
        method: 'PATCH',
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json',
        },
        credentials: 'include',
        body: JSON.stringify(cleanedData)
      });

      // 检查HTTP状态
      if (!response.ok) {
        let errorMessage = '更新用户资料失败';
        try {
          const errorData = await response.json();
          console.error('更新用户资料请求失败:', errorData);
          errorMessage = errorData.error || errorMessage;
          throw new Error(errorMessage);
        } catch (jsonError) {
          // 如果响应不是JSON格式，尝试读取文本
          const textResponse = await response.text();
          console.error('更新用户资料请求失败 (非JSON响应):', textResponse);
          throw new Error(`${errorMessage} (HTTP ${response.status})`);
        }
      }

      const result = await response.json();
      console.log('用户资料更新成功:', result);
      return result;
    } catch (error) {
      console.error('更新用户资料失败:', error);
      throw error;
    }
  },

  /**
   * 上传用户头像
   */
  uploadAvatar: async (file: File) => {
    try {
      const formData = new FormData();
      formData.append('avatar', file);
      
      const response = await fetch('/api/user/avatar', {
        method: 'POST',
        body: formData,
        credentials: 'include',
      });
      
      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || '上传头像失败');
      }
      
      return await response.json();
    } catch (error) {
      console.error('上传头像失败:', error);
      throw error;
    }
  },

  /**
   * 获取用户设置
   */
  getUserSettings: async () => {
    try {
      // 确保请求发送到正确的端点并带有凭证
      const response = await fetch(`/api/user/settings`, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json',
        },
        credentials: 'include',
      });

      if (!response.ok) {
        const errorData = await response.json();
        console.error('获取用户设置请求失败:', errorData);
        throw new Error(errorData.error || '获取用户设置失败');
      }

      return await response.json();
    } catch (error) {
      console.error('获取用户设置失败:', error);
      throw new Error('获取用户设置失败');
    }
  },

  /**
   * 更新用户设置
   */
  updateUserSettings: async (data: any) => {
    try {
      // 确保请求发送到正确的端点并带有凭证
      const response = await fetch('/api/user/settings', {
        method: 'PATCH',
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json',
        },
        credentials: 'include',
        body: JSON.stringify(data)
      });

      if (!response.ok) {
        const errorData = await response.json();
        console.error('更新用户设置请求失败:', errorData);
        throw new Error(errorData.error || '更新用户设置失败');
      }

      return await response.json();
    } catch (error) {
      console.error('更新用户设置失败:', error);
      throw new Error('更新用户设置失败');
    }
  },

  /**
   * 更新主题设置
   */
  updateThemeSettings: async (theme: string, themeColor: string) => {
    try {
      console.log('开始更新主题设置:', { theme, themeColor });
      
      // 确保请求发送到正确的端点并带有凭证
      const response = await fetch('/api/user/settings/theme', {
        method: 'PATCH',
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json',
        },
        credentials: 'include',
        body: JSON.stringify({ theme, themeColor })
      });

      // 检查HTTP状态
      if (!response.ok) {
        let errorMessage = '更新主题设置失败';
        try {
          const errorData = await response.json();
          console.error('更新主题设置请求失败:', errorData);
          errorMessage = errorData.error || errorMessage;
          throw new Error(errorMessage);
        } catch (jsonError) {
          // 如果响应不是JSON格式，尝试读取文本
          const textResponse = await response.text();
          console.error('更新主题设置请求失败 (非JSON响应):', textResponse);
          throw new Error(`${errorMessage} (HTTP ${response.status})`);
        }
      }

      const result = await response.json();
      console.log('主题设置更新成功:', result);
      return result;
    } catch (error) {
      console.error('更新主题设置失败:', error);
      throw error;
    }
  },

  /**
   * 更新通知设置
   */
  updateNotificationSettings: async (settings: any) => {
    try {
      console.log('开始更新通知设置:', settings);
      
      // 确保数据格式正确
      const cleanedSettings = { ...settings };
      
      // 确保请求发送到正确的端点并带有凭证
      const response = await fetch('/api/user/settings/notifications', {
        method: 'PATCH',
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json',
        },
        credentials: 'include',
        body: JSON.stringify(cleanedSettings)
      });

      // 检查HTTP状态
      if (!response.ok) {
        let errorMessage = '更新通知设置失败';
        try {
          const errorData = await response.json();
          console.error('更新通知设置请求失败:', errorData);
          errorMessage = errorData.error || errorMessage;
          throw new Error(errorMessage);
        } catch (jsonError) {
          // 如果响应不是JSON格式，尝试读取文本
          const textResponse = await response.text();
          console.error('更新通知设置请求失败 (非JSON响应):', textResponse);
          throw new Error(`${errorMessage} (HTTP ${response.status})`);
        }
      }

      const result = await response.json();
      console.log('通知设置更新成功:', result);
      return result;
    } catch (error) {
      console.error('更新通知设置失败:', error);
      throw error;
    }
  },

  /**
   * 发送密码重置邮件
   */
  sendPasswordResetEmail: async (email: string) => {
    try {
      return await api.post('/auth/reset-password', { email });
    } catch (error) {
      console.error('发送密码重置邮件失败:', error);
      throw new Error('发送密码重置邮件失败');
    }
  },

  /**
   * 重置密码
   */
  resetPassword: async (token: string, password: string) => {
    try {
      return await api.post('/auth/reset-password/confirm', { token, password });
    } catch (error) {
      console.error('重置密码失败:', error);
      throw new Error('重置密码失败');
    }
  },

  /**
   * 更新用户语言设置
   */
  updateLanguage: async (language: string) => {
    try {
      // 确保请求发送到正确的端点并带有凭证
      const response = await fetch('/api/user/settings/language', {
        method: 'PATCH',
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json',
        },
        credentials: 'include',
        body: JSON.stringify({ language })
      });

      if (!response.ok) {
        const errorData = await response.json();
        console.error('更新用户语言设置请求失败:', errorData);
        throw new Error(errorData.error || '更新用户语言设置失败');
      }

      return await response.json();
    } catch (error) {
      console.error('更新用户语言设置失败:', error);
      throw new Error('更新用户语言设置失败');
    }
  },

  /**
   * 获取用户统计数据
   */
  getUserStats: async (userId: string, queryParams?: string) => {
    try {
      console.log('获取用户统计数据...');
      // 构建请求URL，如果有查询参数则附加
      const url = queryParams ? 
        `/user/${userId}/stats?${queryParams}` : 
        `/user/${userId}/stats`;
      
      // 发送请求并指定不缓存
      return await api.get(url, { cache: 'no-store' });
    } catch (error) {
      console.error('获取用户统计数据失败:', error);
      // 返回一个默认值而不是抛出错误，以便UI可以降级处理
      return {
        stats: {
          projects: { total: 0, active: 0, completed: 0 },
          tasks: { completed: 0, inProgress: 0, pending: 0, review: 0, overdue: 0 }
        }
      };
    }
  },
};

/**
 * 项目相关API
 */
export const projectApi = {
  /**
   * 获取项目列表
   */
  getProjects: async () => {
    try {
      console.log('获取项目列表...');
      const response = await api.get('/project');
      console.log('项目列表获取成功 - 原始响应:', response);
      
      // 处理不同的响应格式
      if (response && typeof response === 'object') {
        // 如果响应已经是数组，直接返回
        if (Array.isArray(response)) {
          console.log('响应已经是数组，直接返回');
          return response;
        }
        
        // 如果响应有data字段并且data是数组，返回data
        if (response.data && Array.isArray(response.data)) {
          console.log('从响应中提取data数组:', response.data);
          return response.data;
        }
        
        // 如果响应有message字段但格式不对，可能是错误
        if (response.message && !response.success) {
          console.error('获取项目列表失败:', response.message);
          throw new Error(response.message);
        }
      }
      
      // 如果响应格式不符合预期，但仍然要尝试处理
      console.warn('响应格式不符合预期，尝试返回原始响应:', response);
      return response || [];
    } catch (error) {
      console.error('获取项目列表失败:', error);
      // 返回空数组而不是抛出错误，这样页面至少可以渲染
      return [];
    }
  },

  /**
   * 获取项目详情
   */
  getProject: async (projectId: string) => {
    try {
      console.log(`获取项目详情 (ID: ${projectId})...`);
      const response = await api.get(`/project?id=${projectId}`);
      console.log('项目详情获取成功:', response);
      return response;
    } catch (error) {
      console.error(`获取项目详情失败 (ID: ${projectId}):`, error);
      throw error;
    }
  },

  /**
   * 创建项目
   */
  createProject: async (data: any) => {
    try {
      console.log('创建项目请求数据:', data);
      const response = await api.post('/project', data);
      console.log('项目创建成功响应:', response);
      return response;
    } catch (error: any) {
      console.error('创建项目失败:', error);
      // 详细记录错误信息
      if (error instanceof ApiError) {
        console.error('API错误详情:', {
          message: error.message,
          status: error.status,
          data: error.data
        });
      }
      throw error;
    }
  },

  /**
   * 更新项目
   */
  updateProject: async (projectId: string, data: any) => {
    try {
      console.log(`更新项目 (ID: ${projectId})`, data);
      const response = await api.put(`/project?id=${projectId}`, data);
      console.log('项目更新成功:', response);
      return response;
    } catch (error) {
      console.error(`更新项目失败 (ID: ${projectId}):`, error);
      throw error;
    }
  },

  /**
   * 删除项目
   */
  deleteProject: async (projectId: string) => {
    try {
      console.log(`删除项目 (ID: ${projectId})...`);
      const response = await api.delete(`/project?id=${projectId}`);
      console.log('项目删除成功:', response);
      return response;
    } catch (error) {
      console.error(`删除项目失败 (ID: ${projectId}):`, error);
      throw error;
    }
  },

  /**
   * 获取项目统计数据
   */
  getProjectStats: async (projectId: string, queryParams?: string) => {
    try {
      console.log('获取项目统计数据...');
      // 构建请求URL，如果有查询参数则附加
      const url = queryParams ? 
        `/api/projects/${projectId}/stats?${queryParams}` : 
        `/api/projects/${projectId}/stats`;
      
      // 发送请求并指定不缓存
      const response = await api.get(url, { cache: 'no-store' });
      console.log('获取到的统计数据:', response);
      return response;
    } catch (error) {
      console.error('获取项目统计数据失败:', error);
      // 返回空对象而不是抛出错误，以避免UI崩溃
      return {};
    }
  },

  /**
   * 获取项目团队成员
   */
  getProjectMembers: (projectId: string) => {
    return api.get(`/projects/${projectId}/members`);
  },

  /**
   * 邀请成员加入项目
   */
  inviteMember: (projectId: string, data: any) => {
    return api.post(`/projects/${projectId}/members/invite`, data);
  },

  /**
   * 更新成员角色
   */
  updateMemberRole: (projectId: string, memberId: string, data: any) => {
    return api.put(`/projects/${projectId}/members/${memberId}`, data);
  },

  /**
   * 移除项目成员
   */
  removeMember: (projectId: string, memberId: string) => {
    return api.delete(`/projects/${projectId}/members/${memberId}`);
  },

  /**
   * 获取项目活动记录
   */
  getProjectActivities: async (projectId: string) => {
    try {
      console.log('获取项目活动记录...');
      const response = await api.get(`/api/projects/${projectId}/activities`);
      
      // 处理API返回格式
      if (response.success && response.data && Array.isArray(response.data)) {
        // 直接返回数据数组
        return response.data;
      } else if (response.data && Array.isArray(response.data)) {
        // 直接返回数组
        return response.data;
      } else if (response && Array.isArray(response)) {
        // 如果响应本身就是数组
        return response;
      } else {
        console.warn('活动数据格式不符合预期:', response);
        return [];
      }
    } catch (error) {
      console.error('获取项目活动记录失败:', error);
      return [];
    }
  },
  
  /**
   * 获取项目文档内容
   */
  getProjectContent: async (projectId: string) => {
    try {
      console.log('获取项目文档内容...');
      return await api.get(`/api/projects/${projectId}/content`);
    } catch (error) {
      console.error('获取项目文档内容失败:', error);
      return { content: '' };
    }
  },
  
  /**
   * 保存项目文档内容
   */
  saveProjectContent: async (projectId: string, content: string) => {
    try {
      console.log('保存项目文档内容...');
      return await api.post(`/api/projects/${projectId}/content`, { content });
    } catch (error) {
      console.error('保存项目文档内容失败:', error);
      throw new Error('保存项目文档内容失败');
    }
  },

  /**
   * 获取项目任务列表
   */
  getProjectTasks: async (projectId: string) => {
    try {
      console.log('获取项目任务列表...');
      return await api.get(`/api/projects/${projectId}/tasks`);
    } catch (error) {
      console.error('获取项目任务列表失败:', error);
      throw new Error('获取项目任务列表失败');
    }
  },
  
  /**
   * 更新任务
   */
  updateTask: async (taskId: string, data: any) => {
    try {
      console.log('更新任务...');
      return await api.put('/task', { ...data, id: taskId });
    } catch (error) {
      console.error('更新任务失败:', error);
      throw new Error('更新任务失败');
    }
  },
};

/**
 * 任务相关API
 */
export const taskApi = {
  /**
   * 获取任务列表
   */
  getTasks: (projectId: string) => {
    return api.get(`/task?projectId=${projectId}`);
  },

  /**
   * 获取任务详情
   */
  getTask: (taskId: string) => {
    return api.get(`/task?id=${taskId}`);
  },

  /**
   * 创建任务
   */
  createTask: (data: any) => {
    return api.post('/task', data);
  },

  /**
   * 更新任务
   */
  updateTask: (taskId: string, data: any) => {
    return api.put('/task', { ...data, id: taskId });
  },

  /**
   * 删除任务
   */
  deleteTask: (taskId: string) => {
    return api.delete(`/task?id=${taskId}`);
  },
};

/**
 * 通知相关API
 */
export const notificationApi = {
  /**
   * 获取通知列表
   */
  getNotifications: () => {
    return api.get('/notifications');
  },

  /**
   * 标记通知为已读
   */
  markAsRead: (notificationId: string) => {
    return api.patch(`/notifications/${notificationId}/read`);
  },

  /**
   * 标记所有通知为已读
   */
  markAllAsRead: () => {
    return api.post('/notifications/mark-all-read');
  },

  /**
   * 删除通知
   */
  deleteNotification: (notificationId: string) => {
    return api.delete(`/notifications/${notificationId}`);
  },
};

// 导出所有API
export default {
  project: projectApi,
  task: taskApi,
  user: userApi,
  notification: notificationApi,
}; 